<template>
	<view class="gift-receive">
		<view class="" v-if="datalist.gift_total_num != datalist.gift_use_num && datalist.is_accept_gift == 0">
			<!-- 顶部商家信息 -->
			<view class="merchant-info">
				<image class="merchant-avatar" :src="datalist.memberinfo.headimg" mode="aspectFill"></image>
				<text class="merchant-name">{{ datalist.memberinfo.nickname }}为您精选了{{ datalist.gift_total_num }}份
					<template v-if="datalist.gift_type == 1">单人礼包</template>
					<template v-if="datalist.gift_type == 2">多人礼包</template>
					<template v-if="datalist.gift_type == 3">随机礼包,您将获得随机一份礼包</template>
				</text>
			</view>

			<!-- 礼物展示区 -->
			<!-- <view class="gift-preview">
				<video v-if="gift.video" class="gift-video" :src="gift.video" poster="gift.poster" object-fit="cover"></video>
			</view> -->

			<!-- 贺卡区域 -->
			<view class="gift-text" v-if="datalist.gift_is_secret == 1">
				<image :src="gift_set.secretpic" mode=""></image>
			</view>
			<view class="gift-content" v-else>
				<view class="gift-card" v-for="(item, index) in datalist.pics" :key="index">
					<view class="gift-card-box">
						<image class="card-image" :src="item"></image>
					</view>
					<!-- <view class="card-message">
						<text class="message-text">{{ gift.message }}</text>
						<text class="message-sender">—— {{ gift.sender }}</text>
					</view> -->
				</view>
			</view>

			<!-- 领取按钮 -->
			<view class="receive-btn" @tap="sendGift" v-if="showButton">
				<text>填写地址收礼</text>
			</view>
			<!-- 送礼弹窗 -->
			<uni-popup ref="giftPopup" type="bottom">
				<view class="address-form">
					<view class="address-box">
						<!-- 顶部标题 -->
						<view class="form-header">
							<view class="img-close" @click="close">
								<image class="img-icon" src="/static/img/close.png" mode=""></image>
							</view>
							<view class="header-title">恭喜您获得礼品</view>

							<image class="gift-preview-sm" :src="datalist.pics[0]"></image>

							<view class="header-subtitle">填写地址就能收礼了</view>
						</view>

						<!-- 倒计时 -->
						<view class="countdown">
							<text class="countdown-num">{{ countdown.hours }}</text>
							<text>:</text>
							<text class="countdown-num">{{ countdown.minutes }}</text>
							<text>:</text>
							<text class="countdown-num">{{ countdown.seconds }}</text>
							<text>后失效</text>
						</view>
					</view>

					<!-- 地址表单 -->
					<form @submit="onSubmit">
						<view class="form-content">

							<view class="form">
								<view class="form-item">
									<text class="label">收货人</text>
									<input class="input" type="text" placeholder="请输入收货人姓名"
										placeholder-style="font-size:28rpx;color:#BBBBBB" name="linkman"
										:value="linkman"></input>
								</view>
								<view class="form-item">
									<text class="label">联系电话</text>
									<input class="input" type="number" maxlength="11" placeholder="请输入手机号"
										placeholder-style="font-size:28rpx;color:#BBBBBB" name="tel"
										:value="tel"></input>
								</view>
								<view class="form-item" v-if="type == 1">
									<text class="label flex0">选择位置</text>
									<text class="flex1" style="text-align:right" :style="area ? '' : 'color:#BBBBBB'"
										@tap="selectzuobiao">{{ area ? area : '请选择您的位置' }}</text>
								</view>
								<view class="form-item form-item-loca" v-else>
									<text class="label flex1">所在地区</text>
									<uni-data-picker ref="picker" class="form-picke" :localdata="items" :border="false"
										:placeholder="regiondata || '请选择省市区'" @change="regionchange"></uni-data-picker>
									<view class="sl-main" @tap="locationSelect">
										<image class="sl-icon" :src="static_url + '/static/img/juli.png'" />
										<view class="sl-tip">定位</view>
									</view>
								</view>
								<view class="form-item">
									<text class="label">详细地址</text>
									<input class="input" type="text" placeholder="请输入详细地址"
										placeholder-style="font-size:28rpx;color:#BBBBBB" name="address"
										:value="address"></input>
								</view>
							</view>


							<!-- 隐私提示 -->
							<view class="privacy-tip">
								*隐私保护：仅供应商发货时能查看您的地址
							</view>
						</view>
						<button class="confirm-btn" :style="'background:' + t('color1') + ''"
							form-type="submit">确认收礼</button>
					</form>
					<!-- 确认按钮 -->
					<!-- <view class="confirm-btn" @tap="onSubmit">
						确认收礼
					</view> -->
				</view>
			</uni-popup>
		</view>
		<view class="gift-claimed-message" v-else>
			<image v-if="isload" :src="gift_set.acceptstatuspic" mode=""></image>
			<view class="msg">
				{{ msg }}
			</view>
		</view>
		<loading v-if="loading" loadstyle="left:62.5%"></loading>
	</view>
</template>

<script>
var app = getApp()
export default {
	data() {
		return {
			countdown: {
				hours: '00',
				minutes: '00',
				seconds: '00'
			},
			timer: null,
			// validityPeriod: 48 * 60 * 60 * 1000,
			linkman: '',
			tel: '',
			area2: '',
			address: '',
			type: 0,
			items: [],
			regiondata: '',
			showCompany: false,
			opt: {},
			datalist: [],
			showButton: true,
			gift_set: '',
			loading: false,
			isload: false,
			msg: "",
			pre_url: app.globalData.pre_url, static_url: app.globalData.static_url,
		}
	},

	onLoad: function (opt) {

		this.opt = app.getopts(opt);

		this.type = this.opt.type || 0;
		var that = this;
		this.getdata();
		app.get('Index/getCustom', {}, function (customs) {
			var url = app.globalData.static_url + '/static/area.json';
			uni.request({
				url: url,
				data: {},
				method: 'GET',
				header: {
					'content-type': 'application/json'
				},
				success: function (res2) {
					that.items = res2.data
				}
			});
		});


	},
	created() {
		this.targetTime = this.orderCreateTime + this.expirationDuration;
		this.startCountdown();
	},
	// 组件销毁时清除定时器
	beforeDestroy() {
		if (this.timer) {
			clearInterval(this.timer)
			this.timer = null
		}
	},
	methods: {
		// 选择地址
		locationSelect: function () {
			var that = this;
			uni.chooseLocation({
				success: function (res) {

					const match = res.address.match(/^(.*?(省|自治区|特别行政区))?(.*?市)?(.*?(区|县|旗))?(.*)$/);


					if (match) {
						let province = match[1] || ''; // 省或自治区
						let city = match[3] || ''; // 市
						let district = match[4] || ''; // 区、县或旗
						let address = match[6].trim(); // 详细地址

						if (province == '' && city != '') {
							province = city;
						}
						that.address = address + res.name;
						that.longitude = res.longitude;
						that.latitude = res.latitude;
						if (province) {
							that.$refs.picker.clear();
							that.regiondata = province + ',' + city + ',' + district;
							that.area2 = province + ',' + city + ',' + district;

						} else {
							that.regiondata = '';
						}
					} else {
						console.log("地址格式不正确");
					}
				},
				fail(e) {
					console.log('选择位置失败：', e);
				}
			});
		},
		// 计算倒计时
		calculateCountdown() {
			try {
				// 获取当前时间戳
				const now = Date.now()

				// 确保 createtime 是正确的时间戳
				let orderCreateTime
				if (this.datalist && this.datalist.createtime) {
					// 如果 createtime 是字符串日期格式，转换为时间戳
					if (typeof this.datalist.createtime === 'string') {
						orderCreateTime = new Date(this.datalist.createtime).getTime()
					} else {
						// 如果已经是时间戳但是秒级，转换为毫秒级
						orderCreateTime = this.datalist.createtime * 1000
					}
				} else {
					return false
				}

				// 计算过期时间
				const expireTime = orderCreateTime

				// 计算剩余时间
				let remainTime = expireTime - now



				if (remainTime <= 0) {
					this.countdown = {
						hours: '00',
						minutes: '00',
						seconds: '00'
					}
					if (this.timer) {
						clearInterval(this.timer)
					}
					uni.showToast({
						title: '礼包已过期',
						icon: 'none'
					})
					return false
				}

				// 计算时分秒
				const hours = Math.floor(remainTime / (1000 * 60 * 60))
				remainTime = remainTime % (1000 * 60 * 60)
				const minutes = Math.floor(remainTime / (1000 * 60))
				remainTime = remainTime % (1000 * 60)
				const seconds = Math.floor(remainTime / 1000)

				// 更新倒计时显示
				this.countdown = {
					hours: hours < 10 ? '0' + hours : hours.toString(),
					minutes: minutes < 10 ? '0' + minutes : minutes.toString(),
					seconds: seconds < 10 ? '0' + seconds : seconds.toString()
				}

				return true
			} catch (error) {
				console.error('倒计时计算错误:', error)
				return false
			}
		},

		// 启动倒计时
		startCountdown() {
			// 先清除可能存在的定时器
			if (this.timer) {
				clearInterval(this.timer)
				this.timer = null
			}

			// 先执行一次计算
			if (!this.calculateCountdown()) {
				return
			}

			// 设置定时器
			this.timer = setInterval(() => {
				if (!this.calculateCountdown()) {
					clearInterval(this.timer)
					this.timer = null
				}
			}, 1000)
		},
		regionchange(e) {
			const value = e.detail.value
			console.log(value[0].text + ',' + value[1].text + ',' + value[2].text);
			this.regiondata = value[0].text + ',' + value[1].text + ',' + value[2].text
			this.area2 = this.regiondata
		},
		getdata: function () {
			var that = this;
			that.loading = true;

			app.post('order/getGiftOrderPics', {
				orderid: that.opt.orderid,
				aid: that.opt.aid,
				ordernum: that.opt.ordernum
			}, function (res) {
				that.loading = false;
				that.isload = true;
				if (res.status == 201) {
					this.showButton = false;
				}
				if (res.status == 200 || res.status == 201) {
					that.datalist = res.data
					that.gift_set = res.data.gift_set
				} else {
					app.error(res.msg)
					that.msg = res.msg
				}

				// 确保数据加载完成后再启动倒计时
				that.$nextTick(() => {
					that.startCountdown()
				})
				if (res.lefttime > 0) {
					interval = setInterval(function () {
						that.lefttime = that.lefttime - 1;
						that.getdjs();
					}, 1000);
				}
				that.loaded();
			});
		},

		// 格式化时间戳
		formatTimestamp(timestamp) {
			if (!timestamp) return null
			// 如果是秒级时间戳，转换为毫秒级
			if (timestamp.toString().length === 10) {
				timestamp *= 1000
			}
			return new Date(timestamp).getTime()
		},

		// 打开送礼弹窗
		sendGift(item) {
			this.selectedGift = item
			this.$refs.giftPopup.open()
		},

		// 关闭弹窗
		closePopup() {
			this.$refs.giftPopup.close()
			this.resetForm()
		},
		close() {
			this.$refs.giftPopup.close()
			this.resetForm()
		},
		onSubmit: function (e) {
			var formdata = e.detail.value;
			let aid = this.opt.aid
			let orderid = this.opt.orderid
			let ordernum = this.opt.ordernum
			let linkman = formdata.linkman
			let tel = formdata.tel
			let area2 = this.area2
			let address = formdata.address

			if (linkman == '' || tel == '' || address == '') {
				app.error('请填写完整信息');
				return;
			}
			app.showLoading('提交中');
			app.post('order/acceptGiftorder', {
				aid: aid,
				orderid: orderid,
				ordernum: ordernum,
				linkman: linkman,
				tel: tel,
				area2: area2,
				address: address
			}, function (res) {
				app.showLoading(false);
				if (res.status == 200) {
					uni.showModal({
						title: '提示',
						content: res.msg,
						success: function (ress) {
							if (ress.confirm) {
								// 执行确认后的操作
								app.goto('/pages/my/usercenter');
							} else {
								// 执行取消后的操作
							}
						}
					})
					return;
					//that.showsuccess(res.data.msg);

				} else {
					app.error(res.msg);

					return;
				}


			});
		}
	}
}
</script>

<style>
.gift-receive {
	/* min-height: 100vh; */
	/* background: #006d3c; */
	padding: 30rpx;

}

.merchant-info {
	display: flex;
	align-items: center;
	/* color: #fff; */
	margin-bottom: 30rpx;
}

.merchant-avatar {
	width: 80rpx;
	height: 80rpx;
	border-radius: 50%;
	margin-right: 20rpx;
}

.merchant-name {
	font-size: 32rpx;
}

.gift-preview {
	width: 100%;
	height: 600rpx;
	background: #fff;
	border-radius: 20rpx;
	overflow: hidden;
	margin-bottom: 30rpx;
}

.gift-video {
	width: 100%;
	height: 100%;
}

.gift-card {
	background: #fff;
	border-radius: 20rpx;
	padding: 30rpx;
	margin-bottom: 30rpx;

}

.gift-card-box {
	height: 500rpx;
}

.card-image {
	width: 100%;
	height: 100%;
	border-radius: 12rpx;
	margin-bottom: 20rpx;
	object-fit: cover;
}

.card-message {
	text-align: center;
	padding: 20rpx;
}

.message-text {
	font-size: 32rpx;
	color: #333;
	line-height: 1.5;
	margin-bottom: 20rpx;
	display: block;
}

.message-sender {
	font-size: 28rpx;
	color: #666;
}

.receive-btn {
	width: 80%;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
	background: #ffa033;
	color: #fff;
	font-size: 32rpx;
	border-radius: 44rpx;
	margin: 0 auto;
	margin-bottom: 30rpx;
}

.expire-tip {
	text-align: center;
	font-size: 26rpx;
	color: #fff;
	opacity: 0.8;
}



.address-form {
	background: #fff;
	border-radius: 20rpx 20rpx 0 0;
	padding: 30rpx;
	position: relative;
}

.form-header {
	text-align: center;
	margin-bottom: 30rpx;
}

.header-title {
	font-size: 32rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 20rpx;
}

.gift-preview-sm {
	width: 200rpx;
	height: 200rpx;
	border-radius: 10rpx;
	margin: 20rpx 0;
}

.header-subtitle {
	font-size: 28rpx;
	color: #666;
}

.countdown {
	text-align: center;
	font-size: 28rpx;
	color: #666;
	margin-bottom: 40rpx;
}

.countdown-num {
	display: inline-block;
	width: 40rpx;
	height: 40rpx;
	line-height: 40rpx;
	text-align: center;
	background: #f5f5f5;
	border-radius: 6rpx;
	color: #ff6b81;
	margin: 0 6rpx;
}

.form {
	width: 94%;
	margin: 20rpx 3%;
	border-radius: 5px;
	background: #FFF;
}

.form-item {
	display: flex;
	align-items: center;
	width: 100%;
	border-bottom: 1px #ededed solid;
	height: 98rpx;
	overflow: hidden;
}

.form-item:last-child {
	border: 0
}

.form-item .label {
	color: #8B8B8B;
	font-weight: bold;
	height: 60rpx;
	line-height: 60rpx;
	text-align: left;
	width: 160rpx;
	padding-right: 20rpx;
	white-space: nowrap;
}

.form-item .input {
	flex: 1;
	height: 60rpx;
	line-height: 60rpx;
	text-align: right
}

.placeholder {
	color: #999;
}

.wechat-address {
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	font-size: 26rpx;
	color: #4CD964;
}

.arrow {
	position: absolute;
	right: 20rpx;
	top: 50%;
	transform: translateY(-50%);
	color: #999;
}

.privacy-tip {
	font-size: 24rpx;
	color: #999;
	margin-top: 20rpx;
}

.confirm-btn {
	width: 100%;
	height: 88rpx;
	line-height: 88rpx;
	text-align: center;
	background: #ffa033;
	color: #fff;
	font-size: 32rpx;
	border-radius: 44rpx;
	margin-top: 40rpx;
}

.img-close {
	width: 40rpx;
	height: 40rpx;
	position: absolute;
	right: 20rpx;
	top: 20rpx;
}

.img-icon {
	width: 100%;
	height: 100%;
}

.gift-claimed-message {
	text-align: center;

}

.message-text {
	font-size: 16px;
	font-weight: bold;
	color: #ff4d4f;
	letter-spacing: 1px;
}

.gift-text {
	display: flex;
	justify-content: center;
	align-items: center;
	margin-top: 40rpx;
	margin-bottom: 40rpx;
	width: 100%;
	height: 600rpx;
}

.gift-text image {
	width: 100%;
	height: 100%;
}

.mystery-gift-text {
	font-size: 22px;
	font-weight: bold;
	color: #ff4081;
	text-align: center;
	letter-spacing: 1.2px;
	background: -webkit-linear-gradient(45deg, #ff6a00, #ee0979);
	-webkit-background-clip: text;
	color: transparent;
	text-shadow: 0px 4px 6px rgba(0, 0, 0, 0.3);
	padding: 5px;
	border-radius: 5px;
}

.address-box {
	background-color: #f7f7f7;
	padding: 20rpx;
	border-radius: 20rpx;
}

.uni-popup__wrapper-box {
	background-color: #fff;
}

.form-item-loca {
	padding-right: 75rpx;
}

.sl-main {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding-left: 15rpx;
	border-left: 1px solid #ededed;
	min-width: 60rpx;
	background-color: #fff;
	position: absolute;
	right: 40rpx;
	padding: 0 20rpx;
}

.sl-tip {
	font-size: 22rpx;
	color: #ba1f25;
}

.sl-icon {
	width: 28rpx;
	height: 28rpx;
}

.msg {
	font-size: 40rpx;
	font-weight: 700;
}
</style>
